import requests
from bs4 import BeautifulSoup
import json
import lxml
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QInputDialog, QTextBrowser)

class Searcher(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500, 200, 650, 500)
        self.setWindowTitle('论文搜索')

        self.lb1 = QLabel('姓名：', self)
        self.lb1.move(60, 80)

        self.lb2 = QLabel('                            ', self)  #leave space for "name"
        self.lb2.move(100, 80)

        self.lb3 = QLabel('注意事项', self)
        self.lb3.move(40, 300)

        self.lb4 = QLabel('1.确保您的输入在DBLP上存在对应的搜索结果。', self)
        self.lb4.move(40, 360)

        self.lb5 = QLabel('2.本软件只提供与您的输入最相近的搜索结果。', self)
        self.lb5.move(40, 390)

        self.lb6 = QLabel('3.如软件闪退，说明您的输入无准确搜索结果。请重启软件，重新输入合适的名字。', self)
        self.lb6.move(40, 420)

        self.lb6 = QLabel('4.如您的输入在DBLP上存在重名的情况，请严格遵循DBLP的命名规范输入，防止结果失配。', self)
        self.lb6.move(40, 450)
        
        self.tb = QTextBrowser(self)  #outputting area
        self.tb.move(350, 60)

        self.bt1 = QPushButton('输入姓名', self)
        self.bt1.move(100, 140)

        self.bt2 = QPushButton('开始搜索', self)
        self.bt2.move(100, 200)

        self.show()

        self.bt1.clicked.connect(self.name)
        self.bt2.clicked.connect(self.search)

    
    def name(self):
        sender = self.sender()
        Searcher.name, ok = QInputDialog.getText(self, '输入姓名', '请输入姓名：')#get the name of the scientist that you want to search
        if ok:
            self.lb2.setText(Searcher.name)
            self.tb.clear()    #once we get a new "name", we need to clear the outputting area

    def search(self):
        #get the website of the searching resault of your name
        url_dblp = 'https://dblp.org/search'
        Name = {'q': Searcher.name}
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\
        Chrome/55.0.2883.87 Safari/537.36'}

        #get the most suitable resault
        r_search = requests.get(url_dblp, params = Name, headers = headers)
        bs_search = BeautifulSoup(r_search.content, "lxml")
        r_list = bs_search.find(class_ = "result-list")
        a = r_list.find_all('a')
        for every_a in a:
            if(Searcher.name == every_a.get_text()):
                real_a = every_a
                break

                 

        #output every title
        r_result = requests.get(real_a.get('href'), headers = headers)
        bs_result = BeautifulSoup(r_result.content, "lxml")
        titles = bs_result.find_all(class_ = "title")
        for title in titles:
            self.tb.append(title.get_text() + '\n\r')